<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 小程序管理
 */
namespace app\system\controller\passport;
use app\common\facade\WechatProgram;
use app\common\model\MemberMiniappOrder;
use app\common\model\Miniapp as minapp;
use app\common\model\MemberMiniappCode;
use think\facade\Request;

class Miniapp extends Common{

    public function initialize() {
        parent::initialize();
        if($this->user->parent_id){
            $this->error('无权限访问,只有创始人身份才允许使用。');
        }
        if(!$this->member_miniapp_id){
            $this->error('未找到所属应用,请先开通应用。');
        }
        $this->assign('pathMaps',[['name'=>$this->member_miniapp->appname,'url'=>'javascript:;'],['name'=>'应用管理','url'=>url("system/passport.setting/index")],['name'=>'小程序','url'=>url("system/passport.setting/edit")]]);
    }

    /**
     * 小程序管理
     * @access public
     */
    public function index(){
        $miniapp = WechatProgram::isTypes($this->member_miniapp_id);
        if(!$miniapp){
            return redirect('system/passport.setting/pushAuth',['id' => $this->member_miniapp_id,'types'=>'program']);
        }
        //查询状态
        $view['code'] = MemberMiniappCode::where(['member_miniapp_id'=>$this->member_miniapp_id,'member_id' => $this->user->id])->find();
        //查询审核状态
        $view['auditid']           = [];
        $view['auditid']['status'] = [];
        if($view['code']['is_commit'] == 3){
            $rel = $miniapp->code->getLatestAuditStatus();
            if($rel['errcode']  == 0){
                $view['auditid'] = $rel;
            }
        }
        //已发布的代码
        $view['update_var'] = 0;
        if($view['code']['is_commit'] == 4){
            $var = MemberMiniappOrder::where(['id' => $this->member_miniapp->miniapp_order_id])->field('update_var')->find();
            if($this->member_miniapp->miniapp->template_id > $var->update_var){
                $view['update_var']        = 1;
                $view['code']['is_commit'] = 1;
            }
        }
        if(!file_exists(PATH_PUBLIC.$view['code']['trial_qrcode'])){
            $view['code']['trial_qrcode'] = '';
        }
        return view()->assign($view);
    }

    /**
     * 提交审核
     * @access public
     */
    public function submitPass(){
        $miniapp = WechatProgram::isTypes($this->member_miniapp_id);
        if(!$miniapp){
            $this->error('微信认证失败');
        }
        $getcate = $miniapp->code->getCategory();  //小程序权限目录
        if($getcate['errcode'] == -1){
            $this->error($getcate['errmsg']);
        }
        $page = $miniapp->code->getPage();  //小程序页面
        if($page['errcode'] != 0){
            $this->error($page['errmsg']);
        }
        $cate = [];
        foreach ($getcate['category_list'] as $key => $value) {
            $cate[$key]['name'] = empty($value['third_class']) ? $value['first_class'].'-'.$value['second_class'] : $value['first_class'].'-'.$value['second_class'].'-'.$value['third_class'];
            $cate[$key]['id']   = empty($value['third_id']) ? $value['first_id'].'-'.$value['second_id'] : $value['first_id'].'-'.$value['second_id'].'-'.$value['third_id'];
        }
        $view['cate'] = $cate;
        $view['page'] = $page['page_list'];
        $view['id']   = $this->member_miniapp_id;
        return view()->assign($view);
    }

    
     /**
     * 以下部分是微信小程序官方操作
     * ###########################################
     * 设置域名
     */
    public function domain(){
        //同步修正域名
        $url['action'] = 'set';
        $url['requestdomain']   = ['https://res.'.Request::rootDomain(),'https://'.$this->web['url']];
        $url['wsrequestdomain'] = ['wss://res.'.Request::rootDomain(),'wss://'.$this->web['url']];
        $url['uploaddomain']    = $url['requestdomain'];
        $url['downloaddomain']  = $url['requestdomain'];
        $miniapp = WechatProgram::isTypes($this->member_miniapp_id);
        if(!$miniapp){
            return json(['code'=>0,'msg'=>'微信认证失败']); 
        }
        $rel = $miniapp->domain->modify($url);
        if($rel['errcode'] > 0){
            return json(['code'=>0,'msg'=>'服务器域名:'.$rel['errmsg']]);
        }
        //设置业务域名
        $subrel = $miniapp->domain->setWebviewDomain(['https://'.Request::host(),'https://res.'.Request::rootDomain()]);
        //更新状态
        $data['is_commit']         = 1;
        $data['member_miniapp_id'] = $this->member_miniapp_id;
        $data['member_id']         = $this->user['id'];
        MemberMiniappCode::edit(['member_miniapp_id'=>$this->member_miniapp_id,'member_id' =>$this->user['id']],$data);
        return json(['code'=>200,'msg'=>'设置域名成功']);
    }

    /**
     * 上传代码
     */
    public function upCode(){
        //读取小程序信息
        $app = minapp::where(['id'=>$this->member_miniapp->miniapp_id,'is_lock'=>0])->find();
        if(empty($app)){
            return json(['code'=>200,'msg'=>'小程序不存在或暂停服务']);
        }
        //上传参数
        $miniapp = WechatProgram::isTypes($this->member_miniapp_id);
        if(!$miniapp){
            return json(['code'=>0,'msg'=>'微信认证失败']); 
        }
        $extJson = [
            'extAppid' =>  $this->member_miniapp->miniapp_appid,
            'ext' => [
                "name" => $this->member_miniapp->appname,
                "attr" => [
                    'host'    => 'https://'.Request::host(),
                    'miniapp' => $this->member_miniapp->service_id,
                ],
            ],
            "window" => ['navigationBarTitleText' => $this->member_miniapp->appname]
        ];
        $miniapp =  $miniapp->code->commit($app->template_id,json_encode($extJson),$app->version,$app->describe);
        //更新信息
        $data['is_commit']         = 2;
        $data['member_miniapp_id'] = $this->member_miniapp_id;
        $data['member_id']         = $this->user->id;
        MemberMiniappCode::edit(['member_miniapp_id'=>$this->member_miniapp_id,'member_id' =>$this->user->id],$data);
        return json(['code'=>200,'msg'=>'上传代码成功']);
    }

     /**
     * 拉取二维码
     */
    public function getQrcode(){
        if(request()->isPost()){
            $miniapp = WechatProgram::isTypes($this->member_miniapp_id);
            if(!$miniapp){
                return json(['code'=>0,'msg'=>'微信认证失败']); 
            }
            $qrcode = $miniapp->code->getQrCode();
            $data['trial_qrcode']      = widget('common/Qrcode/saveQcode',['str' => $qrcode,'qrname' => 'miniapp_'.$this->member_miniapp_id]);
            $data['member_miniapp_id'] = $this->member_miniapp_id;
            $data['member_id']         = $this->user->id;
            MemberMiniappCode::edit(['member_miniapp_id'=>$this->member_miniapp_id,'member_id' =>$this->user->id],$data);
            return json(['code'=>200,'msg'=>'读取体验二维码成功']);
        }else{
            return json(['code'=>0,'msg'=>'读取体验二维码失败']); 
        }
    }

     /**
     * 提交审核
     */
    public function addPass(){
        if(request()->isPost()){
            $data = [
                'cate' => $this->request->param('cate/a'),
                'page' => $this->request->param('page/a'),
                'name' => $this->request->param('name/a'),
                'tag'  => $this->request->param('tag/a'),
            ];
            $validate = $this->validate($data,'Open.addpass');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            } 
            $miniapp = WechatProgram::isTypes($this->member_miniapp_id);
            if(!$miniapp){
                return json(['code'=>0,'msg'=>'微信认证失败']); 
            }   
            //读取分类
            $getcate = $miniapp->code->getCategory();
            if($getcate['errcode'] == -1){
                $this->error($getcate['errmsg']);
            }
            //页面一
            $page[0] = ["address"=> $data['page'][0],"tag"=> $data['tag'][0],"title"=> $data['name'][0]];
            $item[0] = array_merge($page[0],$getcate['category_list'][$data['cate']['0']]);
            //提交审核单
            $rel = $miniapp->code->submitAudit($item);
            if($rel['errcode'] != 0){
                return json(['code'=>0,'msg'=>'提交审核:'.$rel['errmsg']]);
            }
            $code_data['is_commit']         = 3;
            $code_data['member_miniapp_id'] = $this->member_miniapp_id;
            $code_data['member_id']         = $this->user->id;
            $code_data['auditid']           = $rel['auditid'];
            MemberMiniappCode::edit(['member_miniapp_id' => $this->member_miniapp_id,'member_id' => $this->user->id],$code_data);
            return json(['code'=>200,'msg'=>'提交审核了','url'=>url('system/passport.miniapp/index')]);
        }else{
            return json(['code'=>0,'msg'=>'读取体验二维码失败']); 
        }
    }

    /**
     * 强制撤销审核
     * @access public
     */
    public function restPass(){
        if(request()->isPost()){
            $miniapp = WechatProgram::isTypes($this->member_miniapp_id);
            if(!$miniapp){
                return json(['code'=>0,'msg'=>'微信认证失败']); 
            }
            $rel = $miniapp->code->withdrawAudit();
            if($rel['errcode'] == 0){
                $data['is_commit']         = 1;
                $data['member_miniapp_id'] = $this->member_miniapp_id;
                $data['member_id']         = $this->user->id;
                MemberMiniappCode::edit(['member_miniapp_id'=>$this->member_miniapp_id,'member_id' => $this->user->id],$data);
                return json(['code'=>200,'msg'=>'撤回成功']);
            }else{
                return json(['code'=>0,'msg'=>'撤回失败:'.$rel['errmsg']]);
            }
        }else{
            return json(['code'=>0,'msg'=>'读取体验二维码失败']); 
        }
    }

    /**
     * 发布小程序
     */
    public function sendApp(){
        if(request()->isPost()){
            $rel = WechatProgram::isTypes($this->member_miniapp_id)->code->release();
            switch ($rel['errcode']) {
                case 0:
                    //修改发布状态
                    MemberMiniappCode::edit(['member_miniapp_id' => $this->member_miniapp_id,'member_id' =>$this->user->id],['is_commit' => 4,'member_miniapp_id'=>$this->member_miniapp_id,'member_id'=>$this->user->id]);
                    //同步本地版本
                    MemberMiniappOrder::where(['id' => $this->member_miniapp->miniapp_order_id])->update(['update_var' => $this->member_miniapp->miniapp->template_id]);
                    return json(['code'=>200,'msg'=>'发布成功']);
                    break;
                case 85019:
                    return json(['code'=>0,'msg'=>'没有审核版本']);
                    break;
                case 85020:
                    return json(['code'=>0,'msg'=>'审核状态未满足发布']);
                    break;
                case -1:
                    return json(['code'=>0,'msg'=>'系统繁忙']);
                    break;
                default:
                    return json(['code'=>0,'msg'=>$rel['errmsg']]);
                    break;
            }
        }else{
            return json(['code'=>0,'msg'=>'小程序发布失败']); 
        }
    }
}